/**
 * Created by z30 on 15-6-5.
 */

var chars = ['0','1','2','3','4','5','6','7','8','9',
    'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
    'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
    '-','~','!'];

var chars_num = ['0','1','2','3','4','5','6','7','8','9','0'];
var me = require('./t.js');
var logger = require('./log').logger;
var CryptoJS = require('crypto-js');

var crypto = require('crypto');
//公共秘钥
var keys = '49adb3f3dbae23fc';
var key32='9ce62c1836d128cfc875c9026db7564c';

var clearEncoding = 'utf8';
var algorithm = 'aes-128-cbc';
var cipherEncoding = 'base64';
var iv = new Buffer(16);
var iv16 = new Buffer(16);
iv16.fill(0);
iv.fill(0);

/**
 * AES-128-cbc 加密方式
 *
 * @param {object} data 传入的明文字符串
 * @param {function} cb  回调CALLBACK
 * @api public
 */

exports.encodeCipher_cb = function(data,cb){
    try{
        var cipher = crypto.createCipheriv(algorithm,keys,iv);
        //cipher.setAutoPadding(auto_padding=false);
        var cipherChunks = [];
        cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
        cipherChunks.push(cipher.final(cipherEncoding));
        cb(cipherChunks.join(''),null)
    }catch(e){
        cb(null,e)
    }
};

/**
 * AES-128-cbc 解密方式
 *
 * @param {object} data 传入的密文字符串
 * @param {function} cb  回调CALLBACK
 * @api public
 */

exports.decodeCipher_cb = function(enpdata,cb){
    try
    {
        var decipher = crypto.createDecipheriv(algorithm,keys,iv);
        var plainChunks = [];
        plainChunks.push(decipher.update(enpdata,cipherEncoding,clearEncoding));
        plainChunks.push(decipher.final(clearEncoding));
        cb(plainChunks.join(''),null)
    } catch(e) {
        cb(null, e)
    }
};


/**
 * AES-256-CBC 解密方式
 *
 * @param {object} data 传入的密文字符串
 * @api public
 */

exports.decodeCipher = function(data){
    try
    {
        var cipherChunks = [data];
        var decipher = crypto.createDecipher(algorithm, keys);
        var plainChunks = [];
        for (var i = 0;i < cipherChunks.length;i++) {
            plainChunks.push(decipher.update(cipherChunks[i], cipherEncoding, clearEncoding));
        }
        plainChunks.push(decipher.final(clearEncoding));
        return(plainChunks.join(''))
    } catch(e) {
        return (e)
    }
};


/* md5 hash */
exports.md5hash=function(product_name){
    var Buffer = require("buffer").Buffer;
    var buf = new Buffer(product_name);
    var str = buf.toString("binary");
    var crypto = require("crypto");
    return crypto.createHash("md5").update(str).digest("hex");
};

exports.md5 = function (str) {
    return CryptoJS.MD5(str).toString()
}


/* 产生随机数 回调版本 */
exports.get_random=function(n,callback){
    var res = "";
    for(var i = 0; i < n ; i ++) {
        var id = Math.ceil(Math.random()*64);
        res += chars[id];
    }
    //res += chars_num[Math.ceil(Math.random()*10)]
    callback(res);
};

/* 产生随机数 普通版本 */
exports.get_random_normal=function(n){
    var res = "";
    for(var i = 0; i < n ; i ++) {
        var id = Math.ceil(Math.random()*10);
        res += chars_num[id];
    }
    return res;
    //res += chars_num[Math.ceil(Math.random()*10)]
};

/* 产生TOKEN */
exports.get_token=function(n,callback){
    var res = "";
    for(var i = 0; i < n ; i ++) {
        var id = Math.ceil(Math.random()*64);
        res += chars[id];
    }
    //res += chars_num[Math.ceil(Math.random()*10)]
    callback(res);
};


/* 产生TOKEN 正规版本 */
exports.get_token_normal=function(n){
    var res = "";
    for(var i = 0; i < n ; i ++) {
        var id = Math.ceil(Math.random()*64);
        res += chars[id];
    }
    return res;
    //res += chars_num[Math.ceil(Math.random()*10)]
};

/* 手机号码判断 YES 是手机号 NO 不是手机号码*/
exports.ifcellno=function(cellno){
    if (cellno.length==11)
    {
        var reg=/^1\d{10}$/g;
        var res=reg.exec(cellno);
        if (res)
        {
            return true
        } else
        {
            return false
        }

    } else
    {
        return false
    }
};


/*
  统一Response
  res: res对象
  obj: 数据对象
  Attr: Public
 */
exports.res_AllInOne=function(req,res,rtnflag,obj){
    logger.debug(rtnflag+':'+JSON.stringify(obj));
    res.set('content-type','application/json;charset=utf-8');
    res.status('200').end(JSON.stringify({
        'res': rtnflag,
        'info': obj
    }));
};
exports.res_AllInOneError=function(req,res,obj){
    res.set('content-type','application/json;charset=utf-8');
    res.status('403').end(JSON.stringify(
        {
            'res':'-1',
            'info':obj
        }))
};

exports.aes256cbc=function(data){
    var cipher256cbc = crypto.createCipheriv('aes-256-cbc',key32,iv16);
    var encrypted = cipher256cbc.update(data, 'utf8', 'base64');
    encrypted += cipher256cbc.final('base64');
    return encrypted;
    //console.log(encrypted);
};

exports.dateformat=function(format, dt)
{
    var now = dt || new Date();
    var o = {
        "M+": now.getMonth() + 1, //month
        "d+": now.getDate(), //day
        "h+": now.getHours(), //hour
        "m+": now.getMinutes(), //minute
        "s+": now.getSeconds(), //second
        "q+": Math.floor((now.getMonth() + 3) / 3), //quarter
        "S": now.getMilliseconds() //millisecond
    };

    if(/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (now.getFullYear()+"").substr(4 - RegExp.$1.length));
    }

    for(var k in o) {
        if(new RegExp("("+ k +")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
        }
    }
    return format;
};


/* sha1 hash */
exports.sha1digest=function(string){
  var Buffer = require("buffer").Buffer;
  var buf = new Buffer(string);
  var str = buf.toString("binary");
  return crypto.createHash("sha1").update(str).digest("hex");
};

exports.sha1 = function(str){
    return CryptoJS.SHA1(str).toString();
}


/* return mmdd */
exports.dateffmmdd=function(){
   var yda=(new Date()).getFullYear();
   var mda=(new Date().getMonth())+1;
   var dda=(new Date().getDay());
   mda<10?mda='0'+mda:mda=mda;
   dda<10?dda='0'+dda:dda=dda;
    return yda+mda+dda+''
};